﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;
using Dapper.Mapper;
using PortalWeb.Common.Extensions;
using PortalWeb.Core.Entity;
using PortalWeb.Core.IDao;

namespace PortalWeb.DapperDao.Base
{
    public partial class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        public async Task<T> FindAsync(dynamic primaryId)
        {
            return await conn.GetAsync<T>(primaryId as object);
        }

        public async Task<IEnumerable<T>> FindAllAsync()
        {
            return await conn.GetAllAsync<T>();
        }

        public async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
        {
            QueryResult result = DynamicQuery.GetDynamicQuery(_tableName, predicate);
            return  await conn.QueryAsync<T>(result.Sql, (object) result.Param);
        }


        public async Task<int> AddAsync(T entity)
        {
            return await conn.InsertAsync<T>(entity);
        }

        public async Task<T> UpdateAsync(T entity)
        {
            bool b = await conn.UpdateAsync<T>(entity);
            if (b)
            {
                return entity;
            }
            else
            {
                return null;
            }
        }

        public async Task<bool> DeleteAsync(T entity)
        {
            return await conn.DeleteAsync(entity);
        }
    }
}
